package com.cwits.wifi.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.data.beans.FileInfo;
import com.cwits.wifi.ui.dialog.ProgressWindow;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.ui.service.EncodeAVIToMP4Service;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.FileSizeUtil;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.PreferenceUtils;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXFileObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.VideoView;

public class VideoPlayerActivity extends BaseActivity implements View.OnClickListener, IConstant {

    private String tag = this.getClass().getSimpleName();
    private final static int SCREEN_FULL = 0;
    private final static int SCREEN_DEFAULT = 1;
    private final static int PROGRESS_SUCESS = 1000;
    private final static int HIDE_CONTROLER = 1;
    private final static int PAUSE = 3;
    private final static int EXIT_TEXT = 5;
    private final static int PROGRESS_CHANGED = 0;
    private final static int BUFFER = 6;
    private final static int BUFFERING_TAG = 7;
    private final static int EXIT = 8;
    private final static int SET_PAUSE_BUTTON = 9;
    private final static int IS_PAUSE_BUTTON = 10;
    private final static int SEEK_BACKWARD = 11;
    private final static int SEEK_FORWARD = 12;
    private final static int REPLAY = 13;
    private final static int CHANGED_RXBYTES = 15;
    private final static int HIDE_VIDEOCONTROL = 16;
    private final static int FFMPEG_CODE_SUCCESS = 1500;
    private final static int FFMPEG_CODE_FAILED = 1501;

    private ProgressWindow progressWindow;
    private ProgressDialog pd;
    private String defaultPath;
    private List<FileInfo> allDataInfoList = null;
    private String mVideoPath;
    private boolean isPlay = true;
    private SeekBar mSeekBar;
    private RelativeLayout mRlBack;
    private ImageView mImPlay;
    private ImageView mImNext, mImPrev;
    private TextView mTvTime1, mTvTime2;
    private RelativeLayout mRlDel, mRlFullScreen, mRlShare, mRlPho;
    private LinearLayout mLlShareWx, mLlShareOther, mLlShare;
    private Button mBtnCancle;
    private IWXAPI api;
    private String mSharePath;
    public static int WXSceneSession = 0;
    private int position = 0;
    private VideoView mVideoView = null;
    private final static int TIME = 6868;
    private Uri uri;
    private TwoDialog twoDialog;
    private static boolean isPressHome = false;
    private static int videoPlayingPosition = 0;
    private final BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        private final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";//长按Home键 或者 activity切换键
        private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";//短按HOME键
        private final String SYSTEM_DIALOG_REASON_LOCK = "lock";// 锁屏
        private final String SYSTEM_DIALOG_REASON_ASSIST = "assist";// samsung 长按Home键

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    // 短按Home键
                    isPressHome = true;
                    videoPlayingPosition = (int) mVideoView.getCurrentPosition();
                }
            } else if (action.equals(ACTION_ENCORDING_SUCCESS)) {
                //编码完成
                if (null != pd)
                    pd.dismiss();
                showToast(getString(R.string.video_bmwc));
            }
        }
    };
    private RelativeLayout mRlrlTitle;
    private RelativeLayout mRlr1Control;
    private RelativeLayout mRlVideoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this))
        //    return;

        Vitamio.initialize(VideoPlayerActivity.this, getResources().getIdentifier("libarm", "raw", getPackageName()));
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            super.setTranslucen(R.color.transparent);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            mHandler.sendEmptyMessageDelayed(HIDE_VIDEOCONTROL, 3000);

            setContentView(R.layout.activity_video_land);
        } else {
            setContentView(R.layout.activity_video);
        }


        initData();
        initPath();
        initView();

        initVideoView();
        startPlay();

    }

    private void initData() {

        defaultPath = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/video";
        if (allDataInfoList != null) {
            allDataInfoList.clear();
        }
        allDataInfoList = AppUtil.getLocalFileInfo(defaultPath);

        Iterator<FileInfo> stuIter = allDataInfoList.iterator();
        while (stuIter.hasNext()) {
            FileInfo student = stuIter.next();
            if (student.getTitle().substring(18, 22).equals(".JPG") || student.getTitle().length() != 22)
                stuIter.remove();
        }

        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra("video_file");
        position = Integer.parseInt(mVideoPath);

    }

    private void initPath() {
        //String path = allDataInfoList.get(position).getTitle().substring(0, allDataInfoList.get(position).getTitle().lastIndexOf("."));
        //String a = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + path + ".mp4";
        if (FileSizeUtil.fileIs(getMP4Path())) {
            uri = Uri.parse(getMP4Path());
        } else {
            uri = Uri.parse(allDataInfoList.get(position).getPath());
        }

    }

    private String getMP4Path() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + allDataInfoList.get(position).getTitle().substring(0, allDataInfoList.get(position).getTitle().lastIndexOf(".")) + ".mp4";
    }

    @Override
    public void onBackPressed() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            finish();
        }
    }


    private void initView() {
        IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        homeFilter.addAction(ACTION_ENCORDING_SUCCESS);
        registerReceiver(mHomeKeyEventReceiver, homeFilter);

        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);

        mVideoView = (VideoView) findViewById(R.id.video_view);
        mRlVideoView = (RelativeLayout) findViewById(R.id.video_activity_video_view);
        mRlVideoView.setOnClickListener(this);
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            mLlShare = (LinearLayout) findViewById(R.id.video_activity_ll_share);
            mLlShareWx = (LinearLayout) findViewById(R.id.video_activity_ll_share_wx);
            mLlShareOther = (LinearLayout) findViewById(R.id.video_activity_ll_share_other);
            mBtnCancle = (Button) findViewById(R.id.video_activity_btn_cancle);
            mLlShareWx.setOnClickListener(this);
            mLlShareOther.setOnClickListener(this);
            mBtnCancle.setOnClickListener(this);

            mRlDel = (RelativeLayout) findViewById(R.id.video_activity_rl_del);
            mRlDel.setOnClickListener(this);

            mRlShare = (RelativeLayout) findViewById(R.id.video_activity_rl_share);
            mRlPho = (RelativeLayout) findViewById(R.id.video_activity_rl_pho);
            mRlShare.setOnClickListener(this);
            mRlPho.setOnClickListener(this);

            mRlFullScreen = (RelativeLayout) findViewById(R.id.video_display_fullscreen);
            mRlFullScreen.setOnClickListener(this);

            Locale locale = getResources().getConfiguration().locale;
            String language = locale.getLanguage();
            if (language.endsWith("ru")) {
                mRlShare.setVisibility(View.GONE);
            } else {
                mRlShare.setVisibility(View.VISIBLE);
            }
        }
        mRlBack = (RelativeLayout) findViewById(R.id.video_activity_rl_back);
        mRlBack.setOnClickListener(this);

        mImNext = (ImageView) findViewById(R.id.video_activity_im_next);
        mImPrev = (ImageView) findViewById(R.id.video_activity_im_prev);
        mImNext.setOnClickListener(this);
        mImPrev.setOnClickListener(this);

        mSeekBar = (SeekBar) findViewById(R.id.video_activity_seekbar);

        mTvTime1 = (TextView) findViewById(R.id.video_activity_tv_time1);
        mTvTime2 = (TextView) findViewById(R.id.video_activity_tv_time2);
        mImPlay = (ImageView) findViewById(R.id.video_activity_im_play);
        mImPlay.setOnClickListener(this);
/*
        if (mApplication.getIsOffLineMode() == false) {
            disconnectDevice();
            mApplication.setIsOffLineMode(true);
            mApplication.setIsNeedReconnect(true);
        }
*/
        mRlrlTitle = (RelativeLayout) findViewById(R.id.video_activity_rl_title);
        mRlr1Control = (RelativeLayout) findViewById(R.id.video_activity_rl_control);



    }

    private void initVideoView() {

        mVideoView.setOnSeekCompleteListener(new io.vov.vitamio.MediaPlayer.OnSeekCompleteListener() {

            @Override
            public void onSeekComplete(io.vov.vitamio.MediaPlayer mp) {

            }

        });

        mVideoView.setOnErrorListener(new io.vov.vitamio.MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(io.vov.vitamio.MediaPlayer mp, int what, int extra) {
                return false;
            }
        });

        mVideoView.setOnBufferingUpdateListener(new io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener() {

            @Override
            public void onBufferingUpdate(io.vov.vitamio.MediaPlayer mp, int percent) {
            }

        });

        mVideoView.setOnInfoListener(new io.vov.vitamio.MediaPlayer.OnInfoListener() {

            @Override
            public boolean onInfo(io.vov.vitamio.MediaPlayer mp, int what, int extra) {

                switch (what) {

                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:

                        break;

                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:

                        break;

                    case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:

                        break;


                    case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:

                        break;

                    case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:

                        break;

                }

                return true;
            }

        });

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            public void onProgressChanged(SeekBar seekbar,
                                          int progress, boolean fromUser) {
                if (fromUser) {
                    mVideoView.seekTo(progress);

                }
            }

            public void onStartTrackingTouch(SeekBar arg0) {

            }

            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        mVideoView.setOnPreparedListener(new io.vov.vitamio.MediaPlayer.OnPreparedListener() {

            @Override
            protected Object clone() throws CloneNotSupportedException {
                return super.clone();
            }

            @Override
            public void onPrepared(io.vov.vitamio.MediaPlayer mp) {

                int i = (int) mVideoView.getDuration();
                mSeekBar.setMax(i);

                mVideoView.start();
                //startTimer();
                mTvTime2.setText(calculatTime(i));

                mHandler.sendEmptyMessage(SET_PAUSE_BUTTON);
                mHandler.removeMessages(PROGRESS_CHANGED);
                mHandler.sendEmptyMessage(PROGRESS_CHANGED);
                //mHandler.removeMessages(BUFFER);
                //mHandler.sendEmptyMessage(BUFFER);


            }

        });

        mVideoView.setOnCompletionListener(new io.vov.vitamio.MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(io.vov.vitamio.MediaPlayer mp) {
                mSeekBar.setProgress((int) mVideoView.getDuration());
                mTvTime1.setText(calculatTime((int) mVideoView.getDuration()));
                //stopTimer();
                mHandler.removeMessages(PROGRESS_CHANGED);
                isPlay = false;
                mVideoView.seekTo(0);
                mImPlay.setImageResource(R.mipmap.icon_video_play);
                mRlrlTitle.setVisibility(View.VISIBLE);
                mRlr1Control.setVisibility(View.VISIBLE);
                mHandler.removeMessages(HIDE_VIDEOCONTROL);
            }

        });

        mVideoView.setDrawingCacheEnabled(true);
    }

    private void startPlay() {
        if (uri != null && mVideoView != null) {
            mVideoView.setVideoURI(uri);
            mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_LOW);
            isPlay = true;
            mImPlay.setImageResource(R.mipmap.icon_video_stop);
        }
    }


    public void deleteFile() {
        File dirFile = new File(allDataInfoList.get(position).getPath());
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    public void deleteFilePho(String path) {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    private void playNextVideo() {

        if (allDataInfoList.size() - position > 1) {
            //此时有数据
            position = position + 1;
            initPath();
            startPlay();
        } else {
            //此时没有
            showToastLong(getString(R.string.video_last_one));
        }

    }

    private void playPrevVideo() {
        if (position == 0) {
            //此时为第一个
            showToastLong(getString(R.string.video_first_one));
        } else {
            position = position - 1;
            initPath();
            startPlay();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_activity_video_view:
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    if (mRlrlTitle.getVisibility() != View.VISIBLE && mRlr1Control.getVisibility() != View.VISIBLE) {
                        mRlrlTitle.setVisibility(View.VISIBLE);
                        mRlr1Control.setVisibility(View.VISIBLE);
                        mHandler.sendEmptyMessageDelayed(HIDE_VIDEOCONTROL, 3000);
                    } else {
                        mHandler.removeMessages(HIDE_VIDEOCONTROL);
                        mHandler.sendEmptyMessage(HIDE_VIDEOCONTROL);
                    }
                }
                break;
            case R.id.video_activity_rl_back:
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    finish();
                }
                break;
            case R.id.video_activity_rl_del:
                //删除
                showDele();
                //showTwoDialog();
                break;
            case R.id.video_display_fullscreen:
                //视频全屏
                videoFullScreen();
                break;
            case R.id.video_activity_im_next:
                //下一个
                playNextVideo();
                break;
            case R.id.video_activity_im_prev:
                //上一个
                playPrevVideo();
                break;
            case R.id.video_activity_im_play:
                //播放
                if (isPlay) {
                    //player.pause();
                    mVideoView.pause();
                    //stopTimer();
                    mHandler.removeMessages(PROGRESS_CHANGED);
                    isPlay = false;
                    mImPlay.setImageResource(R.mipmap.icon_video_play);
                } else {
                    //player.start();
                    mVideoView.start();
                    //stopTimer();
                    // startTimer();
                    mHandler.removeMessages(PROGRESS_CHANGED);
                    mHandler.sendEmptyMessage(PROGRESS_CHANGED);
                    isPlay = true;
                    mImPlay.setImageResource(R.mipmap.icon_video_stop);
                }
                break;

            case R.id.video_activity_rl_share:
                //分享

                if (mApplication.getIsOffLineMode() == false) {
                    disconnectDevice();
                    mApplication.setIsOffLineMode(true);
                    mApplication.setRealCamera(false);
                    mApplication.setIsNeedReconnect(true);
                }
                mLlShare.setVisibility(View.VISIBLE);
                break;
            case R.id.video_activity_ll_share_wx:
                //微信好友
                //mSharePath = allDataInfoList.get(position).getTitle().substring(0, allDataInfoList.get(position).getTitle().lastIndexOf("."));

                //String a = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lipeibao/168cardev/mp4/" + mSharePath + ".mp4";
                int size = (int) FileSizeUtil.getFileOrFilesSize(getMP4Path(), FileSizeUtil.SIZETYPE_KB);
                if (size == 0) {

                    if (EncodeAVIToMP4Service.getIsEncoding()) {
                        //正在编码
                        int position = (int) ((System.currentTimeMillis() - PreferenceUtils.getLong(getApplication(), TIME_UPDATA_SUCESS, 0)) / 600);
                        showProgressWindow(position);

                        //showToastLong(getString(R.string.video_bmwc));
                    } else {
                        //没有编码，需要手动去编码
                        //showShareDialog();
                        showShare();
                    }
                } else {
                    if (size >= 10240) {
                        showToastLong(getString(R.string.video_wjgd));
                        return;
                    }
                    shareWX(WXSceneSession, getMP4Path());
                }

                //Toast.makeText(this, "功能暂未开放，敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.video_activity_ll_share_other:
                Intent shareIntent1 = new Intent();
                shareIntent1.setAction(Intent.ACTION_SEND);

                //shareIntent.putExtra(Intent.EXTRA_TEXT, "这里是分享内容"); // 分享的内容
                //shareIntent.setType("text/plain"); // 分享发送的数据类型
                shareIntent1.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(getMP4Path())));
                shareIntent1.setType("video/*");
                startActivity(Intent.createChooser(shareIntent1, ""));
                break;
            case R.id.video_activity_btn_cancle:
                //取消分享
                mLlShare.setVisibility(View.GONE);
                break;
        }

    }

    private void showProgressWindow(int position) {


        progressWindow = new ProgressWindow(VideoPlayerActivity.this,playListener);
        progressWindow.setOutsideTouchable(false);
        progressWindow.showPopupWindow(mVideoView);
        progressWindow.setProgress(position);
        mHandler.sendEmptyMessageDelayed(PROGRESS_SUCESS,1000);

    }

    private View.OnClickListener playListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };

    public void saveMyBitmap(Bitmap mBitmap, String bitName) {
        if (mBitmap == null)
            return;
        File f = new File(Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/photo/" + bitName + ".JPG");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void shareWX(int Scene, String videoPath) {
        WXFileObject file = new WXFileObject();
        WXMediaMessage msg = new WXMediaMessage();
        //String pathVideo = mVideoPath;
        file.setFilePath(videoPath);
        msg.mediaObject = file;
        msg.title = getString(R.string.app_name);
        //msg.description = "微信视频分享";
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("file");
        req.message = msg;
        req.scene = Scene;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    private void showShareDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(VideoPlayerActivity.this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(VideoPlayerActivity.this, R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);

        tvInfo.setText(getString(R.string.video_should_zm));

        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                EncodeAVIToMP4Service.addEncodeAVI(allDataInfoList.get(position).getPath());
                startService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));
                pd = ProgressDialog.show(VideoPlayerActivity.this, getString(R.string.dialog_tip), getString(R.string.video_zzbm));
            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);

    }

    private void showShare() {
        twoDialog = new TwoDialog(VideoPlayerActivity.this, getString(R.string.dialog_tip), getString(R.string.video_should_zm), shareListener);
        twoDialog.show();
    }

    private void showDele() {
        twoDialog = new TwoDialog(VideoPlayerActivity.this, getString(R.string.dialog_tip), getString(R.string.video_del), deleFileListener);
        twoDialog.show();
    }

    private View.OnClickListener shareListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    EncodeAVIToMP4Service.addEncodeAVI(allDataInfoList.get(position).getPath());
                    startService(new Intent(MainApplication.getApplication(), EncodeAVIToMP4Service.class));
                    pd = ProgressDialog.show(VideoPlayerActivity.this, getString(R.string.dialog_tip), getString(R.string.video_zzbm));

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private View.OnClickListener deleFileListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    mVideoView.stopPlayback();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            deleteFilePho(allDataInfoList.get(position).getPath().substring(0, allDataInfoList.get(position).getPath().lastIndexOf(".")) + ".JPG");
                            deleteFile();
                            deleteFilePho(getMP4Path());
                        }
                    }).start();
                    finish();

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private void showTwoDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(VideoPlayerActivity.this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(VideoPlayerActivity.this, R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);

        //tvInfo.setText("确认删除该视频");

        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mVideoView.stopPlayback();
                //  mHandler.removeMessages(PROGRESS_CHANGED);
                // deleteFile();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        deleteFilePho(allDataInfoList.get(position).getPath().substring(0, allDataInfoList.get(position).getPath().lastIndexOf(".")) + ".JPG");
                        deleteFile();
                        deleteFilePho(getMP4Path());
                        // deleteFilePho(mVideoPath.substring(0, mVideoPath.lastIndexOf(".")) + ".JPG");
                    }
                }).start();
                finish();

            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);

    }

    private void videoFullScreen() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isPressHome) {
            mVideoView.seekTo(videoPlayingPosition);
            mSeekBar.setProgress(videoPlayingPosition);
            isPressHome = false;
            videoPlayingPosition = 0;
        }

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        position = savedInstanceState.getInt("video_position");
        initPath();
        startPlay();
        mVideoView.seekTo(savedInstanceState.getInt("videoPlayingPosition"));
        mSeekBar.setProgress(savedInstanceState.getInt("videoPlayingPosition"));
        // isPlay = savedInstanceState.getBoolean("video_isplay");
       /* if (isPlay) {
            //播放
        } else {
            //停止
            mVideoView.pause();
            mHandler.removeMessages(PROGRESS_CHANGED);
            isPlay = false;
            mImPlay.setImageResource(R.mipmap.icon_video_play);
        }
        */
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //outState.putBoolean("video_isplay", isPlay);
        outState.putInt("videoPlayingPosition", (int) mVideoView.getCurrentPosition());
        outState.putInt("video_position", position);
    }

    @Override
    protected void onDestroy() {
        //stopTimer();
        //Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
        mVideoView.stopPlayback();
        mHandler.removeMessages(PROGRESS_CHANGED);
        mHandler.removeMessages(PROGRESS_SUCESS);
        unregisterReceiver(mHomeKeyEventReceiver);
        super.onDestroy();
    }

    private String calculatTime(int milliSecondTime) {

        int hour = milliSecondTime / (60 * 60 * 1000);
        int minute = (milliSecondTime - hour * 60 * 60 * 1000) / (60 * 1000);
        int seconds = (milliSecondTime - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;

        if (seconds >= 60) {
            seconds = seconds % 60;
            minute += seconds / 60;
        }
        if (minute >= 60) {
            minute = minute % 60;
            hour += minute / 60;
        }

        String sh = "";
        String sm = "";
        String ss = "";
        if (hour < 10) {
            sh = "0" + String.valueOf(hour);
        } else {
            sh = String.valueOf(hour);
        }
        if (minute < 10) {
            sm = "0" + String.valueOf(minute);
        } else {
            sm = String.valueOf(minute);
        }
        if (seconds < 10) {
            ss = "0" + String.valueOf(seconds);
        } else {
            ss = String.valueOf(seconds);
        }

        return sh + ":" + sm + ":" + ss;
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case PROGRESS_SUCESS:

                    if (EncodeAVIToMP4Service.getIsEncoding()) {
                        //正在编码

                        if(progressWindow.isShowing()){
                            progressWindow.setProgress((int) ((System.currentTimeMillis() - PreferenceUtils.getLong(getApplication(), TIME_UPDATA_SUCESS, 0)) / 600));
                            mHandler.removeMessages(PROGRESS_SUCESS);
                            mHandler.sendEmptyMessageDelayed(PROGRESS_SUCESS,500);
                        }

                    } else {
                        if(progressWindow.isShowing()){
                            progressWindow.setProgress(100);
                            progressWindow.dismiss();
                        }

                        showToastLong(getString(R.string.video_bmwc));

                    }


                    break;

                case PROGRESS_CHANGED:

                    if (mVideoView == null) {
                        return;
                    }
                    mSeekBar.setProgress((int) mVideoView.getCurrentPosition());
                    mTvTime1.setText(calculatTime((int) (mVideoView.getCurrentPosition())));
                    mHandler.sendEmptyMessageDelayed(PROGRESS_CHANGED, 500);
                    break;

                case HIDE_CONTROLER:
                    break;

                case PAUSE:
                    if (mVideoView != null) {
                        mVideoView.pause();
                    }
                    break;

                case SET_PAUSE_BUTTON:

                    break;

                case IS_PAUSE_BUTTON:
                    if (isPlay) {
                        mVideoView.start();

                        mImPlay.setImageResource(R.mipmap.icon_video_play);

                    } else {
                        mVideoView.pause();
                        mImPlay.setImageResource(R.mipmap.icon_video_stop);

                    }

                    isPlay = !isPlay;
                    break;

                case SEEK_BACKWARD:

                    break;

                case SEEK_FORWARD:

                    break;
                case REPLAY:

                    break;
                case CHANGED_RXBYTES:

                    break;
                case HIDE_VIDEOCONTROL:
                    if (VideoPlayerActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        if (mRlrlTitle.getVisibility() == View.VISIBLE && mRlr1Control.getVisibility() == View.VISIBLE) {
                            mRlrlTitle.setVisibility(View.INVISIBLE);
                            mRlr1Control.setVisibility(View.INVISIBLE);
                        }
                    }

                    break;
                case FFMPEG_CODE_SUCCESS:
                    showToast(getString(R.string.video_sucess));
                    break;
                case FFMPEG_CODE_FAILED:
                    showToast(getString(R.string.video_err));
                    break;

            }
            super.handleMessage(msg);
        }
    };

}
